package juc2.lock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * ReentrantLock基本使用示例
 */
public class ReentrantLockBasicDemo {
    // 创建ReentrantLock实例（默认非公平锁，可传入true创建公平锁）
    private final Lock lock = new ReentrantLock();
    private static int count = 0;

    // 用Lock实现同步，替代synchronized方法
    public void increment() {
        lock.lock(); // 显式获取锁
        try {
            // 临界区逻辑（与synchronized块等效）
            System.out.println(Thread.currentThread().getName() + ":" + count);
            count++;
        } finally {
            lock.unlock(); // 必须在finally中释放锁，避免死锁
        }
    }


    public static void main(String[] args) throws InterruptedException {
        ReentrantLockBasicDemo demo = new ReentrantLockBasicDemo();

        // 多线程并发执行
        Thread t1 = new Thread(demo::increment, "Thread1");
        Thread t2 = new Thread(demo::increment, "Thread2");
        t1.start();
        t2.start();
        t1.join();
        t2.join();

        System.out.println("最终计数：" + count); // 输出2（线程安全）
    }
}

